package com.supreme.uploadserver.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;

public class PostReqService extends HttpReqService<PostReqService> {

    @Override
    public JSONObject request() {
        JSONObject respResult = null;

        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 响应模型
        CloseableHttpResponse response = null;

        try {
            // 创建URI对象，并且设置请求参数
            StringBuilder requestUrl = new StringBuilder();
            if (!StringUtils.isBlank(this.getUrl())) {
                requestUrl.append(this.getUrl());
            } else {
                requestUrl.append(this.getEndpoint());
                if (!StringUtils.isBlank(this.getPath())) {
                    requestUrl.append("/");
                    requestUrl.append(this.getPath());
                }
            }

            URI uri = new URIBuilder(String.valueOf(requestUrl))
                    .setParameters(getQuery())
                    .build();
            System.out.println(uri.toString());

            HttpPost httpPost = new HttpPost(uri);

            if (this.getBody() != null) {
                StringEntity stringEntity = new StringEntity(this.getBody().toString(), StandardCharsets.UTF_8);
                httpPost.setEntity(stringEntity);
            }

            response = httpClient.execute(httpPost);

            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析响应数据
                String content = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                respResult = JSONObject.parseObject(content);
            }
        } catch (URISyntaxException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return respResult;
    }
}
